package com.jy.api.controller.MarsCall;

import com.jy.api.dao.CallTranDao;
import com.jy.api.dao.RewardDao;
import com.jy.api.dao.StoreDao;
import com.jy.api.domain.*;
import com.jy.api.enums.PayTypeEnum;
import com.jy.api.exception.CallServiceException;
import com.jy.api.service.*;
import com.jy.api.service.CallService;
import com.jy.api.signUpReq.MarsCallReq.*;
import com.jy.api.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * Created by xiaohua on 2018/11/9.
 */
@RestController
@Slf4j
@RequestMapping(value = "/v1/call", produces = "application/json;charset=utf-8")
public class MarsCallController {


    @Autowired
    private StoreService storeService;
    @Autowired
    private AppraiseNetService netService;
    @Autowired
    private ProductService productService;
    @Autowired
    private AppraiseService appraiseService;
    @Autowired
    private CallService callService;
    @Autowired
    private RewardService rewardService;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private WechatService wechatService;
    @Autowired
    private RewardDao rewardDao;
    @Autowired
    private StoreDao storeDao;
    @Autowired
    private WithdrawService withdrawService;
    @Autowired
    private StoreOrderService storeOrderService;
    @Autowired
    private CallTranService callTranService;
    @Autowired
    private CallTranDao callTranDao;


    @GetMapping("get-marsIndex")
    public ResponseEntity getMarsCallList(@RequestParam("storeId") String storeId) {
        try {
            return ResponseEntity.ok(storeService.findMarsCallIndex(storeId));
        } catch (Exception e) {
            log.info("get-marsIndex is error==> storeId{}", storeId);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    @PostMapping("appraise")
    public ResponseEntity appraiseStore(@RequestBody AppraiseNetRes netRes) {
        try {
            netService.appraiseStore(netRes);
            return ResponseEntity.ok("评价成功");
        } catch (Exception e) {
            log.info("get-netApp is error==>  storeId{}", netRes.getStoreId());
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    @GetMapping("get-gift")
    public ResponseEntity findGift() {
        try {
            return ResponseEntity.ok(productService.findGift());
        } catch (Exception e) {
            log.info("get-gift is error");
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    @PostMapping("appraise-emp")
    public ResponseEntity appraiseEmp(@RequestBody AppraiseEmpReq req) {
        try {
            appraiseService.appraiseEmp(req);
            return ResponseEntity.ok("评价成功");
        } catch (Exception e) {
            log.info("appraise-emp is error ==> storeId{}", req.getStoreId());
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }


    }

    @GetMapping("judge-call")
    public ResponseEntity judgeCallService(@RequestParam("empId") String empId, @RequestParam("storeId") String storeId, @RequestParam("tableNo") String tableNo) {
        try {
            return ResponseEntity.ok(callService.judgeCallService(empId, storeId, tableNo));
        } catch (Exception e) {
            log.info("call-service is error ==> storeId{},e", storeId, e);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PostMapping("call-service")
    public ResponseEntity callService(@RequestBody CallReq req) {
        try {
            return ResponseEntity.ok(callService.callService(req));
        } catch (Exception e) {
            log.info("call-service is error ==> storeId{},e", req.getStoreId(), e);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    @GetMapping("call-finish")
    public ResponseEntity callFinish(@RequestParam("id") int id) {
        try {
            return ResponseEntity.ok(callService.callFinish(id));
        } catch (CallServiceException e) {
            log.info("call-finish is error==> id{}", id);
            return new ResponseEntity(e.getMessage(), HttpStatus.BAD_REQUEST);
        } catch (Exception e) {
            log.info("call-finish is error ==> id{}", id);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    @PostMapping("reward-order")
    public ResponseEntity rewardOrder(@RequestBody RewardOrderReq req) {
        try {
            return ResponseEntity.ok(rewardService.createRewardOrder(req));
        } catch (Exception e) {
            log.info("reward-order is error ==> id{}", req.getStoreId());
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }

    @GetMapping("get-empCall")
    public ResponseEntity getEmpCall(@RequestParam("storeId") String storeId, Pageable pageable) {
        try {
            Store store = storeDao.findOne(storeId);
            if (store.isCall() && (new Date().getTime() - store.getCallEndTime().getTime()) > 0) {
                return new ResponseEntity("店铺语音呼叫已过期,请及时续费！", HttpStatus.BAD_REQUEST);
            }
            return ResponseEntity.ok(callService.findByStoreCallService(storeId, pageable));

        } catch (Exception e) {
            log.info("get-empCall is error ==> storeId{}", storeId);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    @PostMapping("update-work")
    public ResponseEntity updateEmpWork(@RequestBody EmpReq empReq) {
        return ResponseEntity.ok(employeeService.updateEmpWorkStatus(empReq));
    }


    @GetMapping("get-emp")
    public ResponseEntity getEmp(@RequestParam("storeId") String storeId) {
        return ResponseEntity.ok(employeeService.getEmpList(storeId));
    }


    @PostMapping("/scan-code")
    public ResponseEntity rewardPay(@RequestBody CallEmpRes res) {
        PayTypeEnum payType = res.isType() ? PayTypeEnum.PAY_ALIPAY_NATIVE : PayTypeEnum.PAY_WX_NATIVE;
        SwiftPassQRCodePayResult result = paymentService.qrRewardCodePay(String.valueOf(res.getRewardId()), payType);
        Map<String, String> map = new HashMap();
        map.put("payMode", "THIRD_PARTY");
        map.put("url", result.getCodeImgURL());
        if (result.isSuccess()) {
            return ResponseEntity.ok(map);
        } else {
            return ResponseEntity.badRequest().body(result.getErrMsg());
        }
    }


    @GetMapping("get-rewardItem")
    public ResponseEntity getRewardItem(@RequestParam("storeId") String storeId, Pageable pageable) {

        try {
            return ResponseEntity.ok(rewardService.getRewardItem(storeId, pageable));
        } catch (Exception e) {
            log.info("get-rewardItem is error ==> storeId{}", storeId);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }


    @GetMapping("get-ranking")
    public ResponseEntity getRewardRanking(@RequestParam("storeId") String storeId) {
        try {
            return ResponseEntity.ok(rewardService.getRewardRanking(storeId));
        } catch (Exception e) {
            log.info("get-ranking is error ==> storeId{}", storeId);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

   /* @RequestMapping(method = RequestMethod.DELETE, value = "/reward/{rewardId}")
    public ResponseEntity deletePay(@PathVariable String rewardId) {
        SwiftPassReversePaymentResult result = paymentService.cancelThirdPartyPayment(rewardId);
        if (result.isSuccess()) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.badRequest().body(result.getErrMsg());
        }
    }*/


    @RequestMapping(method = RequestMethod.GET, value = "/wechat-binding")
    public ResponseEntity orderBinding(@RequestParam("storeId") String storeId, @RequestParam("orderId") String orderId) {
        try {
            String url = wechatService.getLogUrl(storeId, orderId);
            return new ResponseEntity(url, HttpStatus.OK);
        } catch (Exception ex) {
            log.error("login1 is error==> storeId:{},orderId:{}", storeId, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("rotation-reward")
    public ResponseEntity rotationReward(@RequestParam("id") String id) {

        try {
            Reward reward = rewardDao.findOne(id);
            Result result = null;
            if (reward.getStatus().equals(OrderStatus.FINISHED)) {
                result = new Result(200, "感谢您的打赏，我们会努力做得更好！");
            } else {
                result = new Result(201, "支付中，请等待");
            }
            return ResponseEntity.ok(result);
        } catch (Exception ex) {
            log.error("rotation-reward is error==> orderId:{}", id, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("get-memberInfo")
    public ResponseEntity getMemberInfo(@RequestParam("id") String id) {

        try {
            return ResponseEntity.ok(rewardService.getMemberInfo(id));
        } catch (Exception ex) {
            log.error("get-memberInfo is error==> id:{}", id, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }

    @PostMapping("update-reward")
    public ResponseEntity updateReward(@RequestBody RewardUpdateReq req) {
        try {
            return ResponseEntity.ok(rewardService.updateReward(req));
        } catch (Exception e) {
            log.info("update-reward is error ==> id{}", req.getId());
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }


    }

    @PostMapping("bind")
    public ResponseEntity bing(@RequestBody MemberRewardReq req) {
        return ResponseEntity.ok(rewardService.updateMemberByMemberId(req));
    }

    @GetMapping("getAll")
    public ResponseEntity getAllStore(@RequestParam("type") String type, Pageable pageable) {
        if (StringUtils.contains(type, "TIME")) {
            return ResponseEntity.ok(storeDao.findListByEnabledOrderByExpireTimeDesc(true, pageable));
        } else {
            return ResponseEntity.ok(storeDao.findListByEnabledOrderByCallDesc(true, pageable));
        }

    }

    @PostMapping("update-call")
    public ResponseEntity updateStore(@RequestBody UpdateStoreReq req) {
        return ResponseEntity.ok(storeService.updateStoreByStoreId(req));
    }

    @PostMapping("update-storeReward")
    public ResponseEntity updateReward(@RequestBody UpdateRewardReq req) {

        return ResponseEntity.ok(storeService.updateReward(req));

    }

    @PostMapping("update-zero")
    public ResponseEntity updateZero(@RequestBody UpdateRewardReq req) {
        return ResponseEntity.ok(storeService.updateStoreByZero(req));
    }

    @PostMapping("update-discount")
    public ResponseEntity updateDiscount(@RequestBody UpdateRewardReq req) {
        return ResponseEntity.ok(storeService.updateStoreByDiscount(req));

    }


    @PostMapping("update-storeAccount")
    public ResponseEntity updateStoreAccount(@RequestBody UpdateStoreAccountReq req) {

        return ResponseEntity.ok(withdrawService.updateStoreWithdraw(req));

    }

    @GetMapping("get-storeAccount")
    public ResponseEntity getStoreAccount(Pageable pageable) {
        return ResponseEntity.ok(withdrawService.getAllWithDraw(pageable));

    }

    @GetMapping("get-store")
    public ResponseEntity getStore(@RequestParam("name") String name) {
        return ResponseEntity.ok(storeService.likeStoreName(name));
    }

    @GetMapping("find-allGift")
    public ResponseEntity findAllGift() {
        return ResponseEntity.ok(productService.findAllGift());
    }


    @PostMapping("update-gift")
    public ResponseEntity updateGift(@RequestBody GiftReq req) {
        return ResponseEntity.ok(productService.updateGift(req));
    }

    @PostMapping("set-call")
    public ResponseEntity setStoreCall(@RequestBody SetStoreCallTime callTime) {
        try {
            return ResponseEntity.ok(storeService.setStoreSecond(callTime));
        } catch (Exception e) {
            return new ResponseEntity("系统运行错误", HttpStatus.BAD_GATEWAY);
        }
    }


    @PostMapping("set-callPay")
    public ResponseEntity setStoreCall(@RequestBody CallPayService s) {
        try {
            return ResponseEntity.ok(callTranService.setCallStore(s.getStoreId()));
        } catch (Exception e) {
            return new ResponseEntity("系统运行错误", HttpStatus.BAD_GATEWAY);
        }
    }


    @PostMapping("/callService/scan-code")
    public ResponseEntity callServicePay(@RequestBody CallServicePayReq req) {
        PayTypeEnum payType = req.isType() ? PayTypeEnum.PAY_ALIPAY_NATIVE : PayTypeEnum.PAY_WX_NATIVE;
        SwiftPassQRCodePayResult result = paymentService.qrCallServiceCodePay(req.getId(), payType);
        Map<String, String> map = new HashMap();
        map.put("payMode", "THIRD_PARTY");
        map.put("url", result.getCodeImgURL());
        if (result.isSuccess()) {
            return ResponseEntity.ok(map);
        } else {
            return ResponseEntity.badRequest().body(result.getErrMsg());
        }
    }


    @PostMapping("tran/callBack")
    public ResponseEntity callServiceCallBack(@RequestBody String xml) {
        try {
            storeOrderService.handleCallOrder(xml);
        } catch (Exception ex) {
            log.error("storeCallBack pay fail:{}", xml);
        }
        return new ResponseEntity("isPaymentSuccess", HttpStatus.OK);
    }

    @GetMapping("rotation-tran")
    @Transactional
    public ResponseEntity findByTranId(@RequestParam("id") String id) {
        CallTran one = callTranDao.findOne(id);
        Store store = storeDao.findOne(one.getStoreId());
        Map<String, Object> map = new HashMap<>();
        if (one.getStatus().equals(OrderStatus.FINISHED)) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(store.getCallEndTime());
            cal.add(Calendar.YEAR, 1);
            try {
                store.setCallEndTime(cal.getTime());
                store.setCall(true);
                storeDao.save(store);
                map.put("code", 200);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            map.put("code", 201);
        }
        return ResponseEntity.ok(map);
    }


}
